package com.cyy.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyy.springbootinit.annotation.AuthCheck;
import com.cyy.springbootinit.common.BaseResponse;
import com.cyy.springbootinit.common.DeleteRequest;
import com.cyy.springbootinit.common.ErrorCode;
import com.cyy.springbootinit.common.ResultUtils;
import com.cyy.springbootinit.constant.UserConstant;
import com.cyy.springbootinit.exception.BusinessException;
import com.cyy.springbootinit.exception.ThrowUtils;
import com.cyy.springbootinit.model.dto.readhistory.ReadingHistoryAddRequest;
import com.cyy.springbootinit.model.dto.readhistory.ReadingHistoryEditRequest;
import com.cyy.springbootinit.model.dto.readhistory.ReadingHistoryQueryRequest;
import com.cyy.springbootinit.model.dto.readhistory.ReadingHistoryUpdateRequest;
import com.cyy.springbootinit.model.entity.ReadingHistory;
import com.cyy.springbootinit.model.entity.User;
import com.cyy.springbootinit.model.vo.ReadingHistoryVO;
import com.cyy.springbootinit.service.ReadingHistoryService;
import com.cyy.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 抄表历史表接口
 *
 * @author 程序员cyy</a>
 * @from cyy</a>
 */
@RestController
@RequestMapping("/readingHistory")
@Slf4j
public class ReadingHistoryController {

    @Resource
    private ReadingHistoryService readingHistoryService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建抄表历史表
     *
     * @param readingHistoryAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addReadingHistory(@RequestBody ReadingHistoryAddRequest readingHistoryAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(readingHistoryAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        ReadingHistory readingHistory = new ReadingHistory();
        BeanUtils.copyProperties(readingHistoryAddRequest, readingHistory);
        // 数据校验
        readingHistoryService.validReadingHistory(readingHistory, true);
        // todo 填充默认值
        // 写入数据库
        boolean result = readingHistoryService.save(readingHistory);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newReadingHistoryId = readingHistory.getHistoryId();
        return ResultUtils.success(newReadingHistoryId);
    }

    /**
     * 删除抄表历史表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteReadingHistory(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        ReadingHistory oldReadingHistory = readingHistoryService.getById(id);
        ThrowUtils.throwIf(oldReadingHistory == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = readingHistoryService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新抄表历史表（仅管理员可用）
     *
     * @param readingHistoryUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateReadingHistory(@RequestBody ReadingHistoryUpdateRequest readingHistoryUpdateRequest) {
        if (readingHistoryUpdateRequest == null || readingHistoryUpdateRequest.getHistoryId()<= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        ReadingHistory readingHistory = new ReadingHistory();
        BeanUtils.copyProperties(readingHistoryUpdateRequest, readingHistory);
        // 数据校验
        readingHistoryService.validReadingHistory(readingHistory, false);
        // 判断是否存在
        long id = readingHistoryUpdateRequest.getHistoryId();
        ReadingHistory oldReadingHistory = readingHistoryService.getById(id);
        ThrowUtils.throwIf(oldReadingHistory == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = readingHistoryService.updateById(readingHistory);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取抄表历史表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ReadingHistoryVO> getReadingHistoryVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        ReadingHistory readingHistory = readingHistoryService.getById(id);
        ThrowUtils.throwIf(readingHistory == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(readingHistoryService.getReadingHistoryVO(readingHistory, request));
    }

    /**
     * 分页获取抄表历史表列表（仅管理员可用）
     *
     * @param readingHistoryQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ReadingHistory>> listReadingHistoryByPage(@RequestBody ReadingHistoryQueryRequest readingHistoryQueryRequest) {
        long current = readingHistoryQueryRequest.getCurrent();
        long size = readingHistoryQueryRequest.getPageSize();
        // 查询数据库
        Page<ReadingHistory> readingHistoryPage = readingHistoryService.page(new Page<>(current, size),
                readingHistoryService.getQueryWrapper(readingHistoryQueryRequest));
        return ResultUtils.success(readingHistoryPage);
    }

    /**
     * 分页获取抄表历史表列表（封装类）
     *
     * @param readingHistoryQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ReadingHistoryVO>> listReadingHistoryVOByPage(@RequestBody ReadingHistoryQueryRequest readingHistoryQueryRequest,
                                                               HttpServletRequest request) {
        long current = readingHistoryQueryRequest.getCurrent();
        long size = readingHistoryQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<ReadingHistory> readingHistoryPage = readingHistoryService.page(new Page<>(current, size),
                readingHistoryService.getQueryWrapper(readingHistoryQueryRequest));
        // 获取封装类
        return ResultUtils.success(readingHistoryService.getReadingHistoryVOPage(readingHistoryPage, request));
    }

    /**
     * 分页获取当前登录用户创建的抄表历史表列表
     *
     * @param readingHistoryQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ReadingHistoryVO>> listMyReadingHistoryVOByPage(@RequestBody ReadingHistoryQueryRequest readingHistoryQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(readingHistoryQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        long current = readingHistoryQueryRequest.getCurrent();
        long size = readingHistoryQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<ReadingHistory> readingHistoryPage = readingHistoryService.page(new Page<>(current, size),
                readingHistoryService.getQueryWrapper(readingHistoryQueryRequest));
        // 获取封装类
        return ResultUtils.success(readingHistoryService.getReadingHistoryVOPage(readingHistoryPage, request));
    }

    /**
     * 编辑抄表历史表（给用户使用）
     *
     * @param readingHistoryEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editReadingHistory(@RequestBody ReadingHistoryEditRequest readingHistoryEditRequest, HttpServletRequest request) {
        if (readingHistoryEditRequest == null || readingHistoryEditRequest.getHistoryId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        ReadingHistory readingHistory = new ReadingHistory();
        BeanUtils.copyProperties(readingHistoryEditRequest, readingHistory);
        // 数据校验
        readingHistoryService.validReadingHistory(readingHistory, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = readingHistoryEditRequest.getHistoryId();
        ReadingHistory oldReadingHistory = readingHistoryService.getById(id);
        ThrowUtils.throwIf(oldReadingHistory == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = readingHistoryService.updateById(readingHistory);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
